import router from "./router";
import { allRouters } from "@/router";
const { constantRoutes } = allRouters;
import store from "./store";
// import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

// 深拷贝常量路由
const _constantRoutes = JSON.parse(JSON.stringify(constantRoutes))

const whiteList = GetWhiteList(_constantRoutes); // no redirect whitelist
// 获取白名单数组，进行路由权限控制
function GetWhiteList(rou) {
  let arr = []
  for (const o of rou) {
    // frou && arr.push(`${frou}/${o.path}`) || arr.push(o.path)
    arr.push(o.name)
    if (o?.children && o.children.length > 0) {
      const children = o.children
      // const acd = GetWhiteList(children,o.name)
      const acd = GetWhiteList(children)
      arr = [...arr,...acd]
    }
  }
  return arr
}

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start();

  // set page title
  document.title = getPageTitle(to.meta.title);

  // determine whether the user has logged in
  const hasToken = getToken();
  const hasGetUserInfo = store.getters.name;
  if (hasToken) {
    // 路由跳转
    if (to.path === "/login") {
      if (hasGetUserInfo) {
        next({ path: "/" });
      } else {
        next();
      }
      NProgress.done();
    } else {
      if (hasGetUserInfo) {
        next();
      } else {
        try {
          // get user info
          await store.dispatch("user/getInfo");
          next({ ...to });
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch("user/resetToken");
          next(`/login?redirect=${to.path}`);
          // Message.error(error || "Has Error");
          // next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.name) !== -1) {
      // in the free login whitelist, go directly
      next();
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
